package com.aoxon.cargo.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.cache.FileManager;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.component.MyProgressDialog;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.state.DataState;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.DisplayUtil;
import com.aoxon.cargo.util.ImageUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class SupCameraActivity extends BaseActivity {

	private List<Picture> pictureList = new ArrayList<Picture>();

	private CameraView cv = null;// 用于存放照相的图片
	private Camera camera;

	private LinearLayout llCameraPreciew;
	private LinearLayout llGalleryPicture;
	private HorizontalScrollView hsCameraGalleryPicture;

	private ImageView ivCameraFlash;
	private ImageView ivReturnButton;
	private ImageView ivTakePhotoButton;
	private ImageView ivOpenFolderButton;
	private ImageView ivUserPictureButton;

	private MyProgressDialog myProgressDialog;

	private FileLoader imageLoader = new FileLoader(100, 100, false);
	private FileManager imageManager = new FileManager();

	private Camera.Parameters parameters = null;
	private int flashLightStatic = 0;
	private boolean isChange = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();
		beginShow();
		openCamera();
	}

	/**
	 * 自定义方法
	 * ******************************************************************************************************************************************/

	private void setup() {
		setContentView(R.layout.sup_camera);

		ivCameraFlash = (ImageView) findViewById(R.id.ivCameraFlash);
		ivOpenFolderButton = (ImageView) findViewById(R.id.ivCameraFolder);
		ivReturnButton = (ImageView) findViewById(R.id.ivCameraReturn);
		ivTakePhotoButton = (ImageView) findViewById(R.id.ivCameraTakePhoto);
		ivUserPictureButton = (ImageView) findViewById(R.id.ivCameraOk);

		llCameraPreciew = (LinearLayout) findViewById(R.id.llCameraPreciew);
		llGalleryPicture = (LinearLayout) findViewById(R.id.llCameraGalleryPicture);
		hsCameraGalleryPicture = (HorizontalScrollView) findViewById(R.id.hsCameraGalleryPicture);

		myProgressDialog = new MyProgressDialog(this);

		ivCameraFlash.setOnClickListener(myClickListener);
		ivOpenFolderButton.setOnClickListener(myClickListener);
		ivReturnButton.setOnClickListener(myClickListener);
		ivTakePhotoButton.setOnClickListener(myClickListener);
		ivUserPictureButton.setOnClickListener(myClickListener);
		llCameraPreciew.setOnClickListener(myClickListener);

		if (!SupCache.initialCamera && SupInputGoodsInfoActivity.TO_ADD_GOODS) {
			Intent intent = new Intent(getBaseContext(),
					SupInputGoodsInfoActivity.class);
			startActivity(intent);
			this.finish();
		}

		Gson gson = new Gson();
		String str = gson.toJson(SupCache.pictureList);
		pictureList = gson.fromJson(str, new TypeToken<List<Picture>>() {
		}.getType());
	}

	private void beginShow() {
		if (pictureList != null) {
			for (int i = 0; i < pictureList.size(); i++) {
				if (DataState.HAVE_BUT_DELETE != pictureList.get(i)
						.getPictureState()
						&& DataState.DELETE != pictureList.get(i)
								.getPictureState()) {
					getImageView(pictureList.get(i));
				}
			}
		}
	}

	/**
	 * 打开相机
	 */
	private void openCamera() {
		llCameraPreciew.removeAllViews();
		cv = new CameraView(SupCameraActivity.this);
		llCameraPreciew.addView(cv);
	}

	/**
	 * 回调用的picture 实现里面的onPictureTaken方法 byte[]数组即为照相后获取到的图片信息
	 */
	private Camera.PictureCallback picture = new Camera.PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			// 获取图片并为其命名
			Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			Matrix matrix = new Matrix();
			matrix.preRotate(90);
			int w = bitmap.getWidth();
			int h = bitmap.getHeight();
			Log.i("createPic", "----------------------orgPic w:" + w + ",h:"
					+ h + "-------------------");
			int startX = 0;
			if (w > h) {// 宽和高已对换
				startX = DisplayUtil.dip2px(SupCameraActivity.this, 46);// 46为屏幕上部分
				w = h;
			}
			bitmap = Bitmap.createBitmap(bitmap, startX, 0, w, h, matrix, true);

			File file = new File(imageManager.getPictureDir(),
					System.currentTimeMillis() + ".png");
			Log.i("createPic",
					"----------------------createPic:" + file.getPath() + ",w:"
							+ w + ",h:" + h + ",startX:" + startX
							+ "-------------------");
			try {
				if (!file.exists()) {
					file.createNewFile();
				}
				openCamera();

				FileOutputStream fos = new FileOutputStream(file.getPath());
				bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.close();

				Picture picture = new Picture();
				picture.setPictureState(DataState.CAMERE_INITIAL);
				picture.setPictureUrl(file.getPath());
				ImageUtil.rotaingFile(file.getPath());
				getImageView(picture);
				pictureList.add(picture);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/**
	 * 根据路径获取显示图片
	 * 
	 * @param path
	 */
	private void getImageView(Picture picture) {
		final View cameraItem = getLayoutInflater().inflate(
				R.layout.sup_camera_item, null);
		final ImageView imageView = (ImageView) cameraItem
				.findViewById(R.id.ivCameraItemImage);
		final ImageView ivDeleteButton = (ImageView) cameraItem
				.findViewById(R.id.ivCameraItemDeletebutton);
		final ProgressBar progressBar = (ProgressBar) cameraItem
				.findViewById(R.id.pbCameraItemLoading);
		imageView.setTag(picture.getPictureUrl());
		ivDeleteButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				isChange = true;
				llGalleryPicture.removeView(cameraItem);
				String path = imageView.getTag().toString();
				for (int i = 0; i < pictureList.size(); i++) {
					if (pictureList.get(i).getPictureUrl().equals(path)) {
						switch (pictureList.get(i).getPictureState()) {
						case DataState.INITIAL:
							pictureList.remove(i);
							break;
						case DataState.SUCCESS:
							pictureList.get(i)
									.setPictureState(DataState.DELETE);
							break;
						case DataState.ADD:
							pictureList.get(i).setPictureState(
									DataState.HAVE_BUT_DELETE);
						default:
							break;
						}
						break;
					}
				}

			}
		});
		try {
			if (DataState.SUCCESS == picture.getPictureState()
					|| DataState.ADD == picture.getPictureState()) {
				String path = picture.getPictureUrl() + "s.png";
				imageLoader.displayImage(path, imageView, progressBar, false);
			} else {
				Bitmap bitmap = ImageUtil.getImageBitmap(
						picture.getPictureUrl(), 100, 100);
				imageView.setImageBitmap(ImageUtil.imageCropToSquare(bitmap));
				progressBar.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		llGalleryPicture.addView(cameraItem);
		hsCameraGalleryPicture.setVisibility(View.VISIBLE);
	}

	/**
	 * 初始化相机执行的操作
	 */
	private void initialCameraError() {
		ToastUtil.show(getBaseContext(), "初始化快速相机失败！");
		SupCache.initialCamera = false;
		if (SupInputGoodsInfoActivity.TO_ADD_GOODS) {
			Intent intent = new Intent(getBaseContext(),
					SupInputGoodsInfoActivity.class);
			startActivity(intent);
		}
		SupCameraActivity.this.finish();
	}

	/**
	 * 主要的surfaceView 负责展示预览图片 camera的开关
	 */
	class CameraView extends SurfaceView {
		private SurfaceHolder holder = null;
		private int previewW = 0;
		private int previewH = 0;
		private int pictureW = 0;
		private int pictureH = 0;

		public CameraView(Context context) {
			super(context);
			holder = this.getHolder();
			holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
			holder.addCallback(new SurfaceHolder.Callback() {
				@Override
				public void surfaceDestroyed(SurfaceHolder holder) {
					// TODO Auto-generated method stub
					try {
						camera.stopPreview();
						camera.release();
						camera = null;
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				@SuppressLint("InlinedApi")
				@Override
				public void surfaceCreated(SurfaceHolder holder) {
					// TODO Auto-generated method stub
					try {
						int w = getWidth();
						int h = getHeight();
						// if (h > w) {
						// h = w;
						// }
						// h = w;
						Log.i("camere", "--------------w:" + w + ",h:" + h);
						camera = Camera.open();
						parameters = camera.getParameters();
						// parameters.setPictureFormat(ImageFormat.JPEG);
						// 模式
						List<String> focusModes = parameters
								.getSupportedFocusModes();
						for (String s : focusModes) {
							Log.i("mode", s);
						}
						boolean isContinuousVideo = false;
						if (focusModes
								.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
							isContinuousVideo = true;
							parameters
									.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
							Log.i("focusModes",
									"-----------------支持CONTINUOUS_VIDEO------------------------");
						} else {
							Log.i("focusModes",
									"-----------------不支持CONTINUOUS_VIDEO------------------------");
							parameters
									.setFocusMode(Camera.Parameters.FLASH_MODE_AUTO);
						}
						// parameters.setRotation(90);
						// parameters.setPreviewSize(1024, 768);
						// parameters.setPictureSize(1024, 768);
						camera.setDisplayOrientation(90);
						// 支持分辨率
						if (previewW == 0 || pictureW == 0) {// 首次计算最合适的picture宽高及preview宽高
							List<Camera.Size> pictureSizeList = parameters
									.getSupportedPictureSizes();
							Collections.sort(pictureSizeList,
									new CameraSizeComparator());
							List<Camera.Size> previewSizeList = parameters
									.getSupportedPreviewSizes();
							Collections.sort(previewSizeList,
									new CameraSizeComparator());
							for (Size size : previewSizeList) {
								Log.i("previewSizeList", "pw:" + size.width
										+ ",ph:" + size.height);
								if (size.height >= 480) {
									previewW = size.width;
									previewH = size.height;
									break;
								}
							}
							if (previewW == 0) {
								Camera.Size previewSize = previewSizeList
										.get(previewSizeList.size() - 1);
								previewW = previewSize.width;
								previewH = previewSize.height;
							}
							for (Size size : pictureSizeList) {
								Log.i("pictureSizeList", "w:" + size.width
										+ ",h:" + size.height);
								if (size.height >= 480) {
									pictureW = size.width;
									pictureH = size.height;
									break;
								}
							}
							if (pictureW == 0) {
								Camera.Size pictureSize = pictureSizeList
										.get(pictureSizeList.size() - 1);
								pictureW = pictureSize.width;
								pictureH = pictureSize.height;
							}
						}

						parameters.setPictureSize(pictureW, pictureH);
						parameters.setPreviewSize(previewW, previewH);
						// Log.i("size", "pw:" + previewW + ",ph:" + previewH +
						// ",w:" + pictureW + ",h:" + pictureH);
						// Size size = camera.getParameters().getPictureSize();
						// Size size2 = camera.getParameters().getPreviewSize();
						// Log.i("camere", "**************w:" + size.width +
						// ",h:"
						// + size.height + ",w2:" + size2.width + ",h2:"
						// + size2.height);
						try {
							camera.setParameters(parameters);
						} catch (Exception e) {
							e.printStackTrace();
						}
						camera.startPreview();
						// 设置camera的预览角度
						// 设置holder主要用于surfaceView的图片实时预览，以及获取图片等功能
						camera.setPreviewDisplay(holder);
						//
						// if (!isContinuousVideo) {
						camera.autoFocus(autoFocusCallback);
						// }
					} catch (Throwable t) {
						t.printStackTrace();
						try {
							camera.release();
							camera = null;
						} catch (Exception e) {
							e.printStackTrace();
						}
						initialCameraError();
					}
				}

				@Override
				public void surfaceChanged(SurfaceHolder holder, int format,
						int width, int height) {
					// TODO Auto-generated method stub
					try {
						camera.startPreview();
					} catch (Exception e) {
						e.printStackTrace();
						try {
							camera.release();
							camera = null;
						} catch (Exception inE) {
							inE.printStackTrace();
							initialCameraError();
						}
					}
				}
			});
		}
	}

	/**
	 * 判断关闭相机时应回到的界面
	 */
	private void returnWhere() {
		Intent intent;
		switch (SupCache.from) {
		case 0:
			intent = new Intent(getBaseContext(), SupIndexActivity2.class);
			startActivity(intent);
			break;
		case 1:
			intent = new Intent(getBaseContext(), SupGoodsManagerActivity.class);
			startActivity(intent);
			break;
		case 2:
			break;
		default:
			break;
		}
		SupCameraActivity.this.finish();
	}

	/**
	 * 判断关闭相机时应回到的界面
	 */
	private void goWhere() {
		Intent intent;
		switch (SupCache.from) {
		case 0:
		case 1:
			intent = new Intent(getBaseContext(),
					SupInputGoodsInfoActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		case 2:
			break;
		default:
			break;
		}
		myProgressDialog.dismiss();
		SupCameraActivity.this.finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == MyStateUtil.OPEN_FLODE_RRETURN) {
				isChange = true;
				Picture picture = new Picture();
				picture.setPictureState(DataState.CAMERE_INITIAL);
				picture.setPictureUrl(ImageUtil.getAbsoluteImagePath(
						data.getData(), SupCameraActivity.this));
				getImageView(picture);
				pictureList.add(picture);
			}
		}
	}

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			returnWhere();
		}
		return false;
	}

	/**
	 * 设置各控件的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = null;
			switch (v.getId()) {

			case R.id.ivCameraReturn:
				returnWhere();
				break;

			case R.id.ivCameraTakePhoto:
				// 在捕获图片前进行自动对焦
//				camera.autoFocus(new AutoFocusCallback() {
//					@Override
//					public void onAutoFocus(boolean success, Camera camera) {
						// 从Camera捕获图片
						if (pictureList != null && pictureList.size() >= 12) {
							ToastUtil.show(SupCameraActivity.this,
									"最多只能12张图片，请先删除不要的图片");

						} else {
							camera.takePicture(null, null, picture);
							isChange = true;
						}
//					}
//				});

				break;
			case R.id.ivCameraFolder:
				try {
					intent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent,
							MyStateUtil.OPEN_FLODE_RRETURN);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;

			case R.id.ivCameraOk:
				setResult(RESULT_OK);
				myProgressDialog.show("提示", "请稍候...");
				SupCache.pictureList = pictureList;
				SupCache.isChangePicture = isChange;
				goWhere();
				break;

			case R.id.llCameraPreciew:
				if (hsCameraGalleryPicture.getVisibility() == View.VISIBLE) {
					// hsCameraGalleryPicture.setVisibility(View.GONE);
				} else {
					hsCameraGalleryPicture.setVisibility(View.VISIBLE);
				}
				break;

			case R.id.ivCameraFlash:
				if (0 == flashLightStatic) {
					parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
					ivCameraFlash.setImageResource(R.drawable.light_open);
					flashLightStatic = 1;
				} else {
					parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
					ivCameraFlash.setImageResource(R.drawable.light_close);
					flashLightStatic = 0;
				}
				// camera.setParameters(parameters);
				break;

			default:
				break;
			}
		}

	};

	// 在捕获图片前进行自动对焦
	private AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
		@Override
		public void onAutoFocus(boolean success, Camera camera) {
			// 从Camera捕获图片
			Log.i("autoFocus", "---------------------自动对焦------------------");
			// camera.takePicture(null, null, picture);
			// isChange = true;
		}
	};

	class CameraSizeComparator implements Comparator<Camera.Size> {
		public int compare(Size lhs, Size rhs) {
			long lsize = lhs.width * lhs.height;
			long rsize = rhs.width * lhs.height;
			if (lsize == rsize)
				return 0;
			else if (lsize < rsize)
				return -1;
			else
				return 1;
		}
	}

}
